package com.topvision.util;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.JwtMap;

import java.util.Date;

/**
 * JWT token 帮助类
 */
public class JwtTokenUtil {

    //Sample method to construct a JWT

    public static String createJWT(String id, String subject) {

//The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

//We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Const.API_KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(Const.JWT_ISSUSER)
                .signWith(signatureAlgorithm, signingKey);

//if it has been specified, let's add the expiration
        /*if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }*/

//Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }

    //Sample method to validate and read the JWT
    private  static  void parseJWT(String jwt) {
//This line will throw an exception if it is not a signed JWS (as expected)
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(Const.API_KEY))
                .parseClaimsJws(jwt).getBody();
        System.out.println("ID: " + claims.getId());
        System.out.println("Subject: " + claims.getSubject());
        if(claims.getIssuer().equals(Const.JWT_ISSUSER)){
            System.out.println("验签正确");
        }
        System.out.println("Issuer: " + claims.getIssuer());
        System.out.println("Expiration: " + claims.getExpiration());
    }

    public static boolean verifyToken(String jwt){
        if(!StringUtils.isEmpty(jwt)){
            //This line will throw an exception if it is not a signed JWS (as expected)
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(Const.API_KEY))
                    .parseClaimsJws(jwt).getBody();
            if (claims.getIssuer().equals(Const.JWT_ISSUSER)){
                return  true;
            }
        }

        return  false;
    }

    public static  void main (String[] args) {
        String jwt = createJWT("shengwm","topvision");
        System.out.println(jwt);
        parseJWT(jwt);
    }
}
